﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Musicman.Common.Entities;
using Musicman.Business;
using Musicman.Common.Utilities;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Musicman.Common;

namespace Musicman.Client2
{
    public partial class SettingsForm : Form
    {
        public long UserID { get; set;}
        private User appUser;
        private bool imageChanged = false;
        private byte[] imageData;

        public SettingsForm()
        {
            InitializeComponent();
            this.KeyPreview = true;

        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == Keys.Escape)
            {
                this.DialogResult = DialogResult.Cancel;
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        private void SettingsForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                e.Cancel = true;
                this.Hide();
            }
        }

        public void RefreshData()
        {
            User user = UserManager.Instance.GetUser(UserID, true);
            this.appUser = user;
            byte[] image = UserManager.Instance.LoadProfilePicture(UserID);
            if (image != null)
            {
                MemoryStream ms = new MemoryStream();
                ms.Write(image, 0, image.Length);
                pbProfilePicture.Image = Image.FromStream(ms);
                ms.Close();
            }
            else
            {
                string imagePath = "";
                if (user.PersonSex == Sex.Male)
                {
                    imagePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Resources\john_doe.jpg");
                }
                else
                {
                    imagePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Resources\jane_doe.jpg");
                }
                pbProfilePicture.Image = Image.FromFile(imagePath);
            }
            txtEmail.Text = user.Emailaddress;
            txtFirstName.Text = user.Firstname;
            txtLastName.Text = user.Lastname;
            if (user.PersonSex == Sex.Male)
            {
                radioMale.Checked = true;
            }
            else
            {
                radioFemale.Checked = true;
            }
            cbReceiveMail.Checked = user.MailRequest;
            cbChangePassword.Checked = false;
            txtOldPassword.Text = "";
            txtNewPassword.Text = "";
            txtNewPassword2.Text = "";

            // stats
            lblWebLogs.Text = user.UserStats.TotalLogsWeb.ToString();
            lblClientLogs.Text = user.UserStats.TotalLogsCient.ToString();
            lblTotalLogs.Text = (user.UserStats.TotalLogsWeb + user.UserStats.TotalLogsCient).ToString();
            lblTotalDownloads.Text = user.UserStats.TotalFilesDownloaded.ToString();
            lblTotalTraffic.Text = Converter.LengthGB(user.UserStats.TotalFilesLength);

            // application settings
            bool useDefaultFolder = false;
            Boolean.TryParse(AppSettingsHelper.GetWebConfigValue(Constants.UseDefaultFolder), out useDefaultFolder);
            string defaultFolder = AppSettingsHelper.GetWebConfigValue(Constants.DefaultFolder);
            if (useDefaultFolder)
            {
                radioDefaultFolder.Checked = true;
            }
            else
            {
                radioAsk.Checked = true;
            }
            lblDefaultFolder.Text = defaultFolder;
        }

        // change profile picture
        private void btnChange_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                using (FileStream fs = File.Open(openFileDialog1.FileName, FileMode.Open, FileAccess.Read))
                {
                    imageData = Converter.CreateTumbnail(96, fs);
                    Image img = Image.FromStream(fs);
                    pbProfilePicture.Image = img;
                    imageChanged = true;
                    fs.Close();
                }
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            // validate and update user;
            bool valid = true;
            bool sucess = true;
            StringBuilder erroMsg = new StringBuilder();
            int errorcnt = 0;

            if (txtFirstName.Text == "")
            {
                errorcnt++;
                erroMsg.AppendFormat("{0}: First name field is mandatory", errorcnt);
                erroMsg.AppendLine();
                if (valid)
                {
                    txtFirstName.Focus();
                }
                valid = false;
            }

            if (txtLastName.Text == "")
            {
                errorcnt++;
                erroMsg.AppendFormat("{0}: Last name field is mandatory", errorcnt);
                erroMsg.AppendLine();
                if (valid)
                {
                    txtLastName.Focus();
                }
                valid = false;
            }

            if (cbChangePassword.Checked)
            {
                if (Converter.EncriptPassword(txtOldPassword.Text) != appUser.Password)
                {
                    errorcnt++;
                    erroMsg.AppendFormat("{0}: Old password incorrect", errorcnt);
                    erroMsg.AppendLine();
                    if (valid)
                    {
                        txtOldPassword.Focus();
                    }
                    valid = false;
                }

                if (txtNewPassword.Text == "")
                {
                    errorcnt++;
                    erroMsg.AppendFormat("{0}: new password is mandatory", errorcnt);
                    erroMsg.AppendLine();
                    if (valid)
                    {
                       txtNewPassword.Focus();
                    }
                    valid = false;
                }

                if (txtNewPassword.Text != txtNewPassword2.Text)
                {
                    errorcnt++;
                    erroMsg.AppendFormat("{0}: Values for new password mismatch", errorcnt);
                    erroMsg.AppendLine();
                    if (valid)
                    {
                        txtNewPassword.Focus();
                    }
                    valid = false;
                }
            }

            if (radioDefaultFolder.Checked && lblDefaultFolder.Text == "")
            {
                errorcnt++;
                erroMsg.AppendFormat("{0}: Default folder not set", errorcnt);
                erroMsg.AppendLine();
                if (valid)
                {
                    btnChngeFolder.Focus();
                }
                valid = false;
            }

            if (valid)
            {
                appUser.Firstname = txtFirstName.Text;
                appUser.Lastname = txtLastName.Text;
                appUser.MailRequest = cbReceiveMail.Checked;
                appUser.PersonSex = radioMale.Checked ? Sex.Male : Sex.Female;
                if (cbChangePassword.Checked)
                {
                    appUser.Password = Converter.EncriptPassword(txtNewPassword.Text);
                }
                sucess = UserManager.Instance.UpdateUserProfile(appUser);
            }
            else 
            {
                MessageBox.Show(erroMsg.ToString(), "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                sucess = false;
            }

            // update profile picture
            if (valid && sucess && imageChanged)
            {
                UserManager.Instance.UpdateProfilePicture(UserID, imageData);
                imageChanged = false;
                
            }

            // update application settings
            if (valid && sucess)
            {
                AppSettingsHelper.SetConfigValue(Constants.UseDefaultFolder, (radioDefaultFolder.Checked ? true : false).ToString());
                AppSettingsHelper.SetConfigValue(Constants.DefaultFolder, lblDefaultFolder.Text);
                Program.USE_DOWNLAD_PATH = radioDefaultFolder.Checked ? true : false;
                Program.DOWNLOAD_PATH = lblDefaultFolder.Text;
            }

            if (sucess)
            {
                MessageBox.Show("User profile updated", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                if (Program.RememberMe)
                {
                    using (FileStream fs = File.Open(Program.UserPath, FileMode.Create, FileAccess.Write))
                    {
                        BinaryFormatter bf = new BinaryFormatter();
                        bf.Serialize(fs, appUser);
                        fs.Flush();
                        fs.Close();
                    }
                }
            }
            else
            {
                MessageBox.Show("Error updating profile", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnChngeFolder_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                lblDefaultFolder.Text = folderBrowserDialog1.SelectedPath;
            }
        }
    }
}
